package com.czk.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.czk.common.to.es.SkuEsModel;
import com.czk.common.utils.R;
import com.czk.gulimall.search.config.ElasticSearchConfig;
import com.czk.gulimall.search.constant.EsConstant;
import com.czk.gulimall.search.feign.ProductFeignService;
import com.czk.gulimall.search.service.MallSearchService;
import com.czk.gulimall.search.vo.AttrResponseVo;
import com.czk.gulimall.search.vo.BrandVo;
import com.czk.gulimall.search.vo.SearchParamVo;
import com.czk.gulimall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/1/25 22:07
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParamVo param) {
        // 构建需要检索的dsl语句

        // 封装请求
        SearchRequest searchRequest = buildSearchRequest(param);
        try {
            // 执行检索
            SearchResponse response = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
            // 封装请求数据
            SearchResult searchResult = buildSearchResult(response, param);
            return searchResult;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private SearchRequest buildSearchRequest(SearchParamVo param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 构建dsl
        /**
         * 模糊匹配、过滤（按照属性、分类、品牌、价格区间、库存）
         */
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 构建must,关键字的模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())) {
            // 按照名字和值匹配
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        // 构建过滤条件
        if (param.getCatalog3Id() != null) {
            // 第一个filter
            // 3级分类id查询
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            // 按照品牌id进行过滤
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        if (param.getHasStock() != null) {
            // 是否有库存的过滤条件
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        // 构建价格区间参数
        if (!StringUtils.isEmpty(param.getSkuPrices())) {
            // 构建range查询
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrices().split("_");
            if (s.length == 2) {
                // 价格区间
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                // 小于
                if (param.getSkuPrices().startsWith("_")) {
                    rangeQuery.lte(s[0]);
                }
                if (param.getSkuPrices().endsWith("_")) {
                    rangeQuery.gte(s[0]);
                }
            }
            boolQueryBuilder.filter(rangeQuery);
        }
        // 按照属性查询
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            // attr=1_5寸:8寸&attr=2_16G:8G
            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder nestBoolQuery = QueryBuilders.boolQuery();
                // 拿到数据
                String[] s = attrStr.split("_");
                // 属性id
                String attrId = s[0];
                // 属性值
                String[] attrValues = s[1].split(":");
                nestBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                // 属性是嵌入式查询
                // 不参与评分
                NestedQueryBuilder nestQuery = QueryBuilders.nestedQuery("attrs", nestBoolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestQuery);
            }
        }
        // 将所有查询条件进行封装查询
        sourceBuilder.query(boolQueryBuilder);
        /**
         * 排序、分页、高亮
         */
        // 二
        // 2.1 排序部分
        if (!StringUtils.isEmpty(param.getSort())) {
            String sort = param.getSort();
            // 分割
            String[] s = sort.split("_");
            // 升序还是降序
            SortOrder sortOrder = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            // 字段
            sourceBuilder.sort(s[0], sortOrder);
        }
        // 2.2 分页部分
        // 拿到页码
        Integer pageNum = param.getPageNum();
        int from = (pageNum - 1) * EsConstant.PRODUCT_PAGESIZE;
        sourceBuilder.from(from);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        // 高亮部分
        if (param.getKeyword() != null) {
            // 有模糊匹配进行高亮
            HighlightBuilder builder = new HighlightBuilder();
            // 高亮属性
            builder.field("skuTitle");
            // 前置标签
            builder.preTags("<b style='color:red'>");
            // 后置标签
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }

        /**
         * 聚合分析
         */
        // 1 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        // 属性
        brand_agg.field("brandId").size(50);
        // 品牌聚合的子聚合
        TermsAggregationBuilder brand_name_agg = AggregationBuilders.terms("brand_name_agg");
        brand_name_agg.field("brandName").size(1);
        brand_agg.subAggregation(brand_name_agg);
        TermsAggregationBuilder brand_img_agg = AggregationBuilders.terms("brand_img_agg");
        brand_img_agg.field("brandImg").size(1);
        brand_agg.subAggregation(brand_img_agg);
        // 聚合品牌
        sourceBuilder.aggregation(brand_agg);
        // 2 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catalogId").size(20);
        // 子聚合
        TermsAggregationBuilder catalog_name = AggregationBuilders.terms("catalog_name_agg");
        catalog_name.field("catalogName").size(1);
        catalog_agg.subAggregation(catalog_name);
        // 聚合属性id
        sourceBuilder.aggregation(catalog_agg);

        // 属性聚合 嵌入式聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        // 子聚合
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg");
        attr_id_agg.field("attrs_attrId");
        TermsAggregationBuilder attr_name = AggregationBuilders.terms("attr_name_agg");
        attr_name.field("attrs_attrName").size(1);

        TermsAggregationBuilder attr_value = AggregationBuilders.terms("attr_value_agg");
        attr_value.field("attrs.attrValue").size(50);

        // 设置子聚合
        attr_id_agg.subAggregation(attr_name);
        attr_id_agg.subAggregation(attr_value);
        attr_agg.subAggregation(attr_id_agg);
        // 聚合属性
        sourceBuilder.aggregation(attr_agg);

        System.out.println("构建的dsl" + sourceBuilder.toString());
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }

    /**
     * 封装返回结果
     *
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParamVo param) {
        SearchResult searchResult = new SearchResult();
        // 拿到命中记录
        SearchHits hits = response.getHits();
        // 拿到总记录数
        long total = hits.getTotalHits().value;
        List<SkuEsModel> list = new ArrayList<>();
        if (hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                // 拿到命中的记录
                String sourceAsString = hit.getSourceAsString();

                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    // 拿到高亮的属性
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    // 用高亮属性覆盖原来的值
                    skuEsModel.setSkuTitle(string);
                }
                list.add(skuEsModel);
            }
        }
        // 获取聚合信息
        Aggregations aggregations = response.getAggregations();
        // 分类聚合信息
        ParsedLongTerms catalog_agg = aggregations.get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVoList = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            // 拿到解析到的分类
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            String keyAsString = bucket.getKeyAsString();
            // 分类id
            catalogVo.setCatalogId(Long.parseLong(keyAsString));
            // 子聚合
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            // 拿到数据
            String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            // 设置名称
            catalogVo.setCatalogName(catalog_name);
            catalogVoList.add(catalogVo);
        }

        // 品牌聚合
        ParsedLongTerms brand_agg = aggregations.get("brand_agg");
        List<SearchResult.BrandVo> brandVoList = new ArrayList<>();
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            // 品牌id
            Long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);
            // 品牌名字和图片
            String brand_img = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            String brand_name = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brand_img);
            brandVo.setBrandName(brand_name);
            brandVoList.add(brandVo);
        }
        // 属性聚合
        List<SearchResult.AttrVo> attrVoList = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedStringTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            // 封装vo
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            // 得到属性id
            long attr_id = bucket.getKeyAsNumber().longValue();
            // 属性name
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attr_name = attr_name_agg.getBuckets().get(0).getKeyAsString();
            // 属性值
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> collect = attr_value_agg.getBuckets().stream().map(bucket1 -> {
                String keyAsString = ((Terms.Bucket) bucket1).getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            // 封装属性对象
            attrVo.setAttrId(attr_id);
            attrVo.setAttrName(attr_name);
            attrVo.setAttrValue(collect);
            attrVoList.add(attrVo);
        }

        // 设置属性集合
        searchResult.setAttrs(attrVoList);
        // 设置分类集合
        searchResult.setCatalogs(catalogVoList);
        // 设置品牌集合
        searchResult.setBrands(brandVoList);
        // 设置内容
        searchResult.setProducts(list);
        // 设置当前页码
        searchResult.setPageNum(param.getPageNum());
        // 设置总页码
        int totalPage = ((int) total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE : ((int) total / EsConstant.PRODUCT_PAGESIZE) + 1);
        // 设置总页码
        searchResult.setTotalPages(totalPage);
        List<Integer> pageList = new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            pageList.add(i);
        }
        // 设置可遍历页码
        searchResult.setPageNavs(pageList);
        // 设置总记录数
        searchResult.setTotal(total);
        // 构建面包屑导航功能
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResult.NavVo> navVoList = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                // 分析传递过来的查询参数值
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo attr1 = (AttrResponseVo) r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(attr1.getAttrName());
                } else {
                    // 失败设置为默认，id
                    navVo.setNavName(s[0]);
                }
                // 取消了面包屑以后，
                // 拿到所有的查询条件去掉当前条件
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr, "UTF-8");
                    encode.replace("+", "%20");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = param.get_queryString().replace("&attrs=" + encode, "");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
                return navVo;
            }).collect(Collectors.toList());

            searchResult.setNavs(navVoList);
        }
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            List<SearchResult.NavVo> navs = searchResult.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");
            // 远程查询所有品牌
            R r = productFeignService.brandInfo(param.getBrandId());
            if (r.getCode() == 0) {
                List<BrandVo> brands = (List<BrandVo>) r.getData("brand", new TypeReference<List<BrandVo>>() {
                });
                StringBuilder builder = new StringBuilder();
                String replace="";
                for (BrandVo brand : brands) {
                    builder.append(brand.getBrandName() + ";");
                    replace=replaceQueryString(param,brand.getBrandId()+"","brandId");
                }
                navVo.setNavValue(builder.toString());
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
            }

        }

        System.out.println(JSON.toJSONString(searchResult));
        return searchResult;
    }

    public String replaceQueryString(SearchParamVo param, String value, String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return param.get_queryString().replace("&" + key + "=" + encode, "");
    }
}
